
registerJQueryFunction(function(selector){
		/**
		 * Make a button open a dialog based on the EJS template specified as a
		 * tag property.
		 */
		selector('button[open_dialog]').click(function(){
				openDialog.call(this,
					renderEjs($(this).attr('open_dialog'),$(this).collectExtraArgs()),
					$(this).attr('dialog_title') || null
				);
		});
});

/**
 * Open a dialog with the specified html code and title
 */
function openDialog(html,title,args){
	args=args||{};
	var dialogDiv=$('<div></div>');
	dialogDiv.attr('display','none');
	dialogDiv.attr('container','dialog');
	var mainContainer=$('#mainContainer');
	dialogDiv.htmlJQ(html);
	FB.Canvas.getPageInfo(function(info){
			dialogDiv.dialog({
					title:title,
					height:'auto',
					width:'auto',
					//For some reason, this does not work in the create function...
					maxHeight:screen.availHeight-10,
					show:{effect:'blind',duration:100},
					modal:args.modal,
					close:function(event,ui){
						dialogDiv.remove();
					},
					position:{'my':'center','at':'top+'+(info.scrollTop+screen.height*3/8),'of':mainContainer},
					create:function(){
						//For some reason, this does not work as option...
						$(this).css('max-width',mainContainer.width()-10);
						$(this).css('overflow','auto');
						if(args.targetDialog){
							$('[container=dialog]').filter(function(){return $(this).attr('dialog_id')===args.targetDialog;}).remove();
							$(this).attr('dialog_id',args.targetDialog);
						}
						if(args.refreshAction){
							$(this).attr('action',args.refreshAction);
							$(this).attr('no_send_on_click',true);
							$(this).attr('autotrigger','refresh-user-panel');
							$(this).attr('data-callback','rerender');
						}
					}
			});
	});
	return dialogDiv;
}

/**
 * Open a dialog directly from an AJAX JSON response.
 */
function openDialogFromResponse(data){
	openDialog.call(this,renderEjs(data),data.title,{
			targetDialog:data.target_dialog,
			refreshAction:data.refresh_action
	});
}
